package com.sky.service.impl;


import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Autowired
    private OrderMapper orderMapper;
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Double> turnoverList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);

            dateList.add(begin);
        }
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status",Orders.COMPLETED);

            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        String joinData = StringUtils.join(dateList, ",");
        String joinTurnover = StringUtils.join(turnoverList, ",");

        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(joinData);
        turnoverReportVO.setTurnoverList(joinTurnover);
        return turnoverReportVO;
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> userList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);



            Map map = new HashMap<>();
            map.put("end",endTime);
            Integer user = userMapper.sumByMap(map);
            user = user == null ? 0: user;
            userList.add(user);
            map.put("begin",beginTime);
            Integer newUser = userMapper.sumByMap(map);
            newUser = newUser == null ? 0 : newUser;
            newUserList.add(newUser);

        }
        String joinData = StringUtils.join(dateList, ",");
        String joinUser = StringUtils.join(userList, ",");
        String joinNewUSer = StringUtils.join(newUserList, ",");
        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(joinData);
        userReportVO.setNewUserList(joinNewUSer);
        userReportVO.setTotalUserList(joinUser);

        return userReportVO;
    }

    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> orderList = new ArrayList<>();
        List<Integer> validOrderList = new ArrayList<>();


        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);

            dateList.add(begin);
        }
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);


            Map map = new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            Integer order = orderMapper.countByMap(map);
            order = order == null ? 0 : order;
            orderList.add(order);

            map.put("status",Orders.COMPLETED);
            Integer validOrder = orderMapper.countByMap(map);
            validOrder = validOrder == null ? 0 : validOrder;
            validOrderList.add(validOrder);
        }

        Integer total = 0;
        Integer valid = 0;
        for (Integer integer : orderList) {
            total += integer;
        }
        for (Integer integer : validOrderList) {
            valid +=integer;
        }


        String joinData = StringUtils.join(dateList, ",");
        String joinOrder = StringUtils.join(orderList, ",");
        String joinValidOrder = StringUtils.join(validOrderList, ",");


        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setDateList(joinData);
        orderReportVO.setOrderCountList(joinOrder);
        orderReportVO.setValidOrderCountList(joinValidOrder);
        orderReportVO.setTotalOrderCount(total);
        orderReportVO.setValidOrderCount(valid);
        orderReportVO.setOrderCompletionRate(((double)valid/(double)total));
        return orderReportVO;
    }

    @Override
    public SalesTop10ReportVO gettopStatistics(LocalDate begin, LocalDate end) {


        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        Map map = new HashMap<>();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status",Orders.COMPLETED);


        List<GoodsSalesDTO> list = orderMapper.getSaleTop(map);

        List<String> nameList = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());

        List<Integer> numberList = list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());


        String joinnumber = StringUtils.join(numberList, ",");
        String joinname = StringUtils.join(nameList, ",");

        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        salesTop10ReportVO.setNameList(joinname);
        salesTop10ReportVO.setNumberList(joinnumber);
        return salesTop10ReportVO;
    }

    @Override
    public void export(HttpServletResponse response) {
        //1.查询数据
        LocalDate localDateBegin = LocalDate.now().minusDays(30);
        LocalDate localDateEnd = LocalDate.now().minusDays(1);
        LocalDateTime begin = LocalDateTime.of(localDateBegin, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(localDateEnd, LocalTime.MAX);


        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);

        //2.插入excel表格

        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);

            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间："+begin+"至"+end);
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());


            for (int i = 0; i < 30; i++) {
                LocalDate date = localDateBegin.plusDays(i);
                BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                XSSFRow row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData1.getTurnover());
                row.getCell(3).setCellValue(businessData1.getValidOrderCount());
                row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData1.getUnitPrice());
                row.getCell(6).setCellValue(businessData1.getNewUsers());


            }

            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            in.close();
            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        //3.导出
    }
}
